<template>

  <el-input v-model="path"></el-input>
  <el-button @click="download">下载文件</el-button>
  <el-upload
      class="upload-demo"
      :onchange="handleChange"
      :auto-upload="false"
      drag
  >
    <el-icon class="el-icon--upload">
      <upload-filled/>
    </el-icon>
    <div class="el-upload__text">
      Drop file here or <em>click to upload</em>
    </div>
    <template #tip>
      <div class="el-upload__tip">
        上传radius路径文件
      </div>
    </template>
  </el-upload>
  <el-row>
    <el-col :span="10" style="border: 2px solid #509bef;border-radius: 2px">
      <el-button type="primary" @click="calculation">计算最新账号对应pon</el-button>
      <el-scrollbar max-height="140px" ref="scrollbar">
        <p v-for="item in count" :key="item" class="scrollbar-demo-item">
          {{ item }}
        </p>
      </el-scrollbar>
    </el-col>
    <el-col :span="8">
      <el-button type="primary" @click="downloadFileWithAxios">下载最新账号对应pon</el-button>
    </el-col>
  </el-row>





<!--  <el-row v-for="i in 5" :key="i">-->
<!--    <el-col :span="12">-->
<!--      处理xx-->
<!--    </el-col>-->
<!--    <el-col :span="12">-->
<!--      <el-icon color="#00ff00" :size="20"><CircleCheckFilled/></el-icon>-->
<!--    </el-col>-->
<!--  </el-row>-->
</template>

<script setup>
import {ElMessage} from "element-plus"
import {UploadFilled} from '@element-plus/icons-vue'
import axios from "../axios";
import {nextTick, ref} from "vue";

const count = ref([""])
const scrollbar = ref(null);
const add = (msg) => {
  count.value.push(msg)
  nextTick(() => {
    const scrollbarDom = scrollbar.value.$el.querySelector('.el-scrollbar__wrap');
    scrollbarDom.scrollTop = scrollbarDom.scrollHeight;
  });
}
function handleChange(e) {
  const formData = new FormData();
  formData.append('file', e.target.files[0]);
  formData.append('path', "/temp/t.xlsx");
  try {
    axios.post('/anh/file/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    }).catch(e=>{
      console.log(e)
    });
    ElMessage({
      showClose: true,
      message: '上传成功',
      type: 'success',
    })
  } catch (error) {
    console.log(error)
  }
}

function downloadFileWithAxios() {
  axios.get(
      '/anh/file/downloadbypath?path=/temp/radius.csv',
      {
        responseType: 'blob' // 设置响应类型为 blob，以便获取文件流
      }
  ).then((response) => {
    const blob = new Blob([response.data], {type: response.headers['content-type']});

    // 获取后端设置的文件名
    const contentDisposition = response.headers['content-disposition'];
    console.log(contentDisposition)
    const fileNameMatch = contentDisposition && contentDisposition.match(/filename=(["']?)([^"']+)\1/);
    const fileName = fileNameMatch && fileNameMatch[1] ? decodeURIComponent(fileNameMatch[1]) : 'default_file.zip';

    const a = document.createElement('a');
    a.href = URL.createObjectURL(blob);
    a.download = fileName;

    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
  }).catch((error) => {
    console.error(error);
  });
}

function calculation() {
  var webSocket = new WebSocket(`ws://192.168.67.56:8082/task-ws/radius?token=${localStorage.getItem("token")}`);
  webSocket.onmessage=(e)=>{
    add(e.data)
    if(e.data==="end"){
      webSocket.close()
    }
  }
  webSocket.onclose=()=>{
    console.log("关闭socket")
  }
  axios.post("/anh/analyse/radius1").catch(e => {
    console.log(e)
  })
  ElMessage({
    showClose: true,
    message: '正在计算',
    type: 'success',
  })
}

const path=ref("")
function download(){
  axios.get(
      '/anh/file/downloadbypath?path='+path.value,
      {
        responseType: 'blob', // 设置响应类型为 blob，以便获取文件流
        timeout : 1000000
      }
  ).then((response) => {
    const blob = new Blob([response.data], {type: response.headers['content-type']});

    // 获取后端设置的文件名
    const contentDisposition = response.headers['content-disposition'];
// 先提取出文件名部分（这里假设格式是固定的，从 `filename=` 之后开始提取）
    const encodedFileName = contentDisposition.split('filename=')[1];
// 对提取出的编码后的文件名进行解码
    const decodedFileName = decodeURIComponent(encodedFileName);

    const a = document.createElement('a');
    a.href = URL.createObjectURL(blob);
    a.download = decodedFileName;

    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
  }).catch((error) => {
    console.error(error);
  });
}
</script>

<style scoped>

</style>